#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>

#define MAX_FILES 50

struct Node {
    char *fileName;
    time_t createTime;
    struct Node *next;
};

void deleteList(struct Node* head) {
    struct Node* tmp;

    while (head != NULL) {
        tmp = head;
        head = head->next;
        free(tmp->fileName);
        free(tmp);
    }
}

int main() {
    DIR *dir;
    struct dirent *entry;
    struct Node *head = NULL;
    int file_count = 0;

while(1)
{

    dir = opendir("/mnt"); // 替换成你的目录路径
    if (dir == NULL) {
        perror("Unable to open directory");
        return EXIT_FAILURE;
    }

    // 读取目录中的文件
    while ((entry = readdir(dir)) != NULL) {
        if (file_count < MAX_FILES) {
            struct stat fileStat;
            char filePath[255];
            sprintf(filePath, "/mnt/%s", entry->d_name);

            if (stat(filePath, &fileStat) == 0) {
                // 分配新节点并保存文件名和创建时间
                struct Node* newNode = malloc(sizeof(struct Node));
                newNode->fileName = strdup(entry->d_name);
                newNode->createTime = fileStat.st_mtime;
                newNode->next = head;
                head = newNode;
                file_count++;
            }
        } else {
            struct Node* current = head;
            struct Node* prev = NULL;
            struct Node* oldest = head;

            // 找到创建时间最早的文件
            while (current->next != NULL) {
                if (current->next->createTime < oldest->createTime) {
                    prev = current;
                    oldest = current->next;
                }
                current = current->next;
            }

            // 删除文件
            char filePath[255];
            sprintf(filePath, "/mnt/%s", oldest->fileName);
            printf("Deleting: %s\n", filePath);
            if (unlink(filePath) == 0) {
                printf("Deleted: %s\n", filePath);
            } else {
                perror("Unable to delete file");
            }

            // 释放节点
            free(oldest->fileName);
            free(oldest);

            // 更新链表头和文件计数
            if (prev != NULL) {
                prev->next = NULL;
            } else {
                head = NULL;
            }
            file_count--;

            break; // 超出文件数量限制，退出循环
        }
    }

    // 清理链表
    deleteList(head);
    closedir(dir);
sleep(1);
}
    return EXIT_SUCCESS;
}

